import random
import time

def number_guessing_game():
    """猜数字游戏主函数"""
    print("欢迎来到猜数字游戏！")
    time.sleep(1)
    
    # 让玩家选择难度
    print("\n请选择难度级别：")
    print("1. 简单 (1-50，最多8次机会)")
    print("2. 中等 (1-100，最多6次机会)")
    print("3. 困难 (1-200，最多5次机会)")
    
    while True:
        try:
            difficulty = int(input("请输入难度编号 (1/2/3): "))
            if difficulty in [1, 2, 3]:
                break
            else:
                print("请输入1、2或3选择难度")
        except ValueError:
            print("请输入有效的数字")
    
    # 根据难度设置参数
    if difficulty == 1:
        max_number = 50
        max_attempts = 8
    elif difficulty == 2:
        max_number = 100
        max_attempts = 6
    else:
        max_number = 200
        max_attempts = 5
    
    # 生成随机数
    secret_number = random.randint(1, max_number)
    attempts = 0
    
    print(f"\n我已经想好了一个1到{max_number}之间的数字")
    print(f"你有{max_attempts}次机会猜出它")
    
    # 游戏主循环
    while attempts < max_attempts:
        try:
            # 获取玩家猜测
            guess = int(input(f"\n请输入你的猜测 ({attempts + 1}/{max_attempts}): "))
            
            # 检查猜测是否在有效范围内
            if guess < 1 or guess > max_number:
                print(f"请输入1到{max_number}之间的数字")
                continue
                
            attempts += 1
            
            # 检查猜测结果
            if guess < secret_number:
                print("猜小了！再试一次")
            elif guess > secret_number:
                print("猜大了！再试一次")
            else:
                # 猜对了
                print(f"\n恭喜你！你用了{attempts}次就猜对了！")
                print(f"秘密数字就是 {secret_number}")
                break
                
        except ValueError:
            print("请输入一个有效的数字")
    
    # 如果用完了所有机会
    if attempts == max_attempts and guess != secret_number:
        print(f"\n游戏结束！你已经用完了所有{max_attempts}次机会")
        print(f"秘密数字是 {secret_number}")
    
    # 询问是否再玩一次
    play_again = input("\n想再玩一次吗？(y/n): ").lower()
    if play_again == 'y':
        number_guessing_game()
    else:
        print("\n谢谢参与！再见！")

# 启动游戏
if __name__ == "__main__":
    number_guessing_game()
    